<?php
/**
 * Note: 应用渠道CPA
 * Date: 2021/12/30
 */
namespace App\Http\Controllers\Admin;

use App\Models\Game\Center\AppAppid;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;

class AppAppidController extends CurdController
{
    protected string $classModel = AppAppid::class;

    // protected string $allowChannels = "kuaishou,douyin,baidu,tencent,alipay,shanyan";

    protected array $searchFields = [
        // 'source' => self::FIELD_TYPE_NUMERIC,
        'channel' => self::FIELD_TYPE_NORMAL,
        'package' => self::FIELD_TYPE_NORMAL,
    ];

    protected array $orderFields = [
        'channel' => 'ASC',
        'package' => 'ASC',
    ];

    /**
     * 保存之前校验
     * @param Request $request
     */
    public function storeBefore(Request $request)
    {
        $request->validate([
            'channel' => "required|string",
            'package' => [
                'required',
                Rule::unique('gameCenter.app_appid')->where(function ($query) use ($request) {
                    return $query->where('channel', $request->channel);
                }),
            ],
            'remark' => 'sometimes',
        ], [
            'package.unique' => '当前平台已绑定该包名',
        ]);
    }

    /**
     * 更新之前校验
     * @param Request $request
     */
    public function updateBefore(Request $request)
    {
        $request->validate([
            'channel' => "required|string",
            'package' => [
                'required',
                Rule::unique('gameCenter.app_appid')->ignore($request->id)->where(function ($query) use ($request) {
                    return $query->where('channel', $request->channel);
                }),
            ],
            'remark' => 'sometimes',
        ], [
            'package.unique' => '当前平台已绑定该包名',
        ]);
    }

    /**
     * 批量更新
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function batch(Request $request)
    {
        foreach ($request->appids as $channel => $appid) {
            $model = new $this->classModel();
            $model->updateOrCreate([
                'package' => $request->package,
                'channel' => $channel,
            ],[
                'appid' => $appid,
                'remark' => $request->remark,
            ]);
        }
        return responseMessage();
    }
}
